package com.fiwizone.ultimateshoppinglist;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class ListEdit extends Activity {

	private EditText mTitleText;
    private Long mRowId;
    private ShoppingData mDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new ShoppingData(this);
        mDbHelper.open();
        
        setContentView(R.layout.list_edit);
       
        mTitleText = (EditText) findViewById(R.id.title);
      
        Button confirmButton = (Button) findViewById(R.id.confirm);
       
        mRowId = savedInstanceState != null ? savedInstanceState.getLong(ShoppingData.KEY_ROWID) : null;
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();            
			mRowId = extras != null ? extras.getLong(ShoppingData.KEY_ROWID) : null;
		}
		
		populateFields();
       
        confirmButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
            	if (saveState()) {
            		setResult(RESULT_OK);
            		finish();
            	}
            }
          
        });
    }
    
    private void populateFields() {
        if (mRowId != null && mRowId != 0) {
            Cursor list = mDbHelper.fetchList(mRowId);
            startManagingCursor(list);
            mTitleText.setText(list.getString(
    	            list.getColumnIndexOrThrow(ShoppingData.KEY_TITLE)));
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        
        // check to see if mRowId is null
        // passing null to putLong causes exception.
        if (mRowId != null) {
        	outState.putLong(ShoppingData.KEY_ROWID, mRowId);
        }
    }
    
    @Override
    protected void onPause() {
        super.onPause();        
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }
    
    private boolean saveState() {
        String title = mTitleText.getText().toString();
        
        // check to see if we have anything to save.
        if (null == title || "".equals(title)) {
        	Toast.makeText(this, "Title cannot be empty", Toast.LENGTH_SHORT).show();
        	return false;
        }

        if (mRowId == null || mRowId == 0) {
            long id = mDbHelper.createList(title);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateList(mRowId, title);
        }
        
        return true;
    }
}
